package com.cershy.chatroomserver.interceptor;

import com.cershy.chatroomserver.annotation.UrlFree;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 拦截器 - 支持 @UrlFree 注解跳过权限校验
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是 Controller 方法且带有 @UrlFree 注解，则放行
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(UrlFree.class)) {
                return true; // 放行
            }

            // TODO: 这里可以添加登录校验逻辑，例如从 header 获取 token 或 session
            // String token = request.getHeader("Authorization");
            // if (!isValidToken(token)) {
            //     response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录");
            //     return false;
            // }
        }

        return true; // 默认放行
    }
}
